import { Component, Input, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Utils } from '../utils/utils';
/**
 * 文件下载的根路径，由公共脚本生成。
 */
declare var fileDownloadRoot: string;
/**
 * 本组件用于算成文件下载链接。
 * @example
 * 用法:
 * 在app.moudle.ts中:
 * import { IFileLinkModule} from 'iisp-ng';
    NgModule({
    imports: [IFileLinkModule,...]
 * 在html中:
 * <i-file-link [fileUri]="item.uri" ></i-file-link>
 */
@Component( {
    selector: "i-file-link",
    template: `
    <a href="{{resolveDownloadUrl(fileUri)}}" target="_blank"><span class="filedownload"><i class="fa fa-{{getFileIcon()}}"></i>{{getLabel()}}</span></a>
    `
} )
export class IFileLinkComponent {
    @Input() fileUri: string;
    @Input() labelKey: string;
    fileDownloadRoot = fileDownloadRoot;
    fileTypes = {
        image: [".png", ".jpg", ".jpeg", ".bmp", ".gif"],//图片文件的后缀名
        word: [".doc", ".docx"],//word文件的后缀名
        excel: [".xls", ".xlsx"],//excel文件的后缀名
        powerpoint: [".ppt", ".pptx"],
        audio: [".wav", ".mp3", ".ogg", ".flac", ".ape"],
        video: [".mov", ".mp4", ".avi", ".asf", ".rm", ".rmvb", ".mpeg"],
        pdf: [".pdf"],//pdf文件的后缀名
        text: [".txt", ".csv", ".xml", ".text", ".tsv"],
        achive: [".zip", ".gz", ".tar", ".7z", ".rar", ".jar", ".war", ".ear", ".tgz"],//pdf文件的后缀名
        code: [".js", ".ts", ".java", ".c", ".sql", ".htm", ".html", , ".css"]//代码的后缀名
    }
    getLabel(): string {
        if ( this.labelKey ) {
            return Utils.resolveLocalizedMessage( this.labelKey );
        }
        return ""
    }
    getFileExt(): string {
        let i = this.fileUri.lastIndexOf( "." );
        if ( i > -1 ) {
            return this.fileUri.substring( i );
        }
        return null;
    }
    getFileIcon(): string {
        let fe = this.getFileExt();
        if ( fe ) {
            for ( let ftypes in this.fileTypes ) {
                for ( let ft of this.fileTypes[ftypes] ) {
                    if ( ft == fe ) {
                        return 'file-' + ftypes + '-o';
                    }
                }
            }
        }
        return "file";
    }
    /**
 * 生成下载链接。
 * @param uri 附件的相对路径
 */
    resolveDownloadUrl( uri: string ): string {
        return fileDownloadRoot + encodeURI( uri );
    }
}

@NgModule( {
    imports: [CommonModule],
    exports: [IFileLinkComponent],
    declarations: [IFileLinkComponent]
} )
export class IFileLinkModule { }